package com.lqq.school.shiro;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //subject ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultSecurityManager);

        //添加shiro内置过滤器
        /**
         * anno：无需认证就可以访问
         * authc：必须认证了才能访问
         * user：必须拥有记住我 功能才能用
         * perms：拥有对某个资源的权限才能访问
         * role：拥有某个角色权限才能访问
         */

       //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权

        //放行的
        filterMap.put("/index.html", "anon");
        filterMap.put("/static/", "anon");
        filterMap.put("/", "anon");
        filterMap.put("/login", "anon");
        filterMap.put("/toLogin", "anon");
        filterMap.put("/toRegister", "anon");
        filterMap.put("/register", "anon");
        filterMap.put("/register.html", "anon");
        filterMap.put("/css/**", "anon");
        filterMap.put("/img/**", "anon");

        //拦截，除了上述页面，其余都要认证才能进
        filterMap.put("/**", "authc");
        filterMap.put("/admin/**", "roles[admin]");
        //授权的

        bean.setFilterChainDefinitionMap(filterMap);

        //设置未授权的请求
        //bean.setUnauthorizedUrl("/noauth");
        //model.addAttribute("msg","没有权限,请先登录！！！");
        //设置登录请求
        bean.setLoginUrl("/toLogin");
        return bean;
    }


    //securityManager
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //绑定realm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }


    //创建realm对象
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
